package com.sanmubird.mywebframework.indicator.domain.service;

import com.alibaba.fastjson.JSONObject;
import com.sanmubird.mywebframework.indicator.domain.ability.IndicatorAbility;
import com.sanmubird.mywebframework.indicator.domain.gateway.IndicatorGateway;
import com.sanmubird.mywebframework.indicator.domain.model.Indicator;
import com.sanmubird.mywebframework.indicator.domain.model.IndicatorValueType;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Objects;


/**
 * @author sam
 */
@Service
public class IndicatorAbilityImpl implements IndicatorAbility {

    private final IndicatorExecutorService indicatorExecutorService;
    private final IndicatorGateway indicatorGateway;

    public IndicatorAbilityImpl(IndicatorExecutorService indicatorExecutorService, IndicatorGateway indicatorGateway) {
        this.indicatorExecutorService = indicatorExecutorService;
        this.indicatorGateway = indicatorGateway;
    }

    public static final String PARAMS = "params";

    @Override
    public JSONObject getIndicatorData(IndicatorConfig indicatorConfig, JSONObject queryParams) {
        JSONObject ret = new JSONObject();
        if (Objects.isNull(indicatorConfig)) {
            return ret;
        }
        Indicator indicator = JSONObject.parseObject(indicatorConfig.getConfig(), Indicator.class);
        indicator.setValueType(IndicatorValueType.from(indicatorConfig.getValueType()));
        // 提取指标参数
        String indicatorCode = indicatorConfig.getIndicatorCode();
        JSONObject indicatorParams = extractIndicatorParam(queryParams, indicatorCode);
        Object object = indicatorExecutorService.internalExecute(indicator, indicatorParams);
        ret.put(indicatorCode, object);
        return ret;
    }

    @Override
    public JSONObject getIndicatorData(String variableCode, JSONObject queryParams) {
        IndicatorConfig indicatorConfig = indicatorGateway.supplyIndicatorConfigBy(variableCode);
        return getIndicatorData(indicatorConfig, queryParams);
    }


    /**
     * 提取指标参数 如果指标传了单独参数，覆盖页面参数
     *
     * @param queryParams  queryParams
     * @param variableCode variableCode
     * @return JSONObject
     */
    private JSONObject extractIndicatorParam(JSONObject queryParams, String variableCode) {
        JSONObject indicatorParams = new JSONObject();
        if (queryParams.containsKey(PARAMS)) {
            indicatorParams.putAll(queryParams.getJSONObject(PARAMS));
        }
        // 指标参数不为空则覆盖全局参数
        if (!ObjectUtils.isEmpty(queryParams.get(variableCode))) {
            indicatorParams.putAll(queryParams.getJSONObject(variableCode));
        }
        return indicatorParams;
    }

}
